import { createSSRApp } from "vue";
import App from "./App.vue";
import uviewPlus from '@/uni_modules/uview-plus'

//数字处理
import numeral from 'numeral'
import chs from 'numeral/locales/chs'
numeral.locale('chs')

//日期时间
import dayjs from 'dayjs'
import isoWeekday from 'dayjs/plugin/isoWeek'
import relativeTime from 'dayjs/plugin/relativeTime'
import _ from 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
dayjs.extend(isoWeekday)
dayjs.extend(relativeTime)

import dayjs_util from './utils/dayjs_utils.js'

//数据处理
import lodash from 'lodash'
import * as at from 'array.prototype.at' 
at.shim(); // 使用shim方法

//网络
import axiosCreator from '@/utils/axiosCreator.js'
import netTool from '@/utils/net-file-storage.js'

//地理
import geo from '@/utils/geographic'

//屏幕
// import Screen from '@/utils/screen.js'
// let screen = new Screen()


// // #ifndef H5
// process = {}
// process.env = {}
// process.env.LOGGER_LEVEL= "info"
// // #endif

//缓存
// import {LRUCache} from 'lru-cache'

// let cache5s = new LRUCache({max:500,ttl:5 * 1000})
// let cache10s = new LRUCache({max:500,ttl:10 * 1000})
// let cache15s = new LRUCache({max:500,ttl:15 * 1000})
// let cache30s = new LRUCache({max:500,ttl:30 * 1000})
// let cache1m = new LRUCache({max:500,ttl:60 * 1000})

//状态 & 持久
import {createPinia} from 'pinia'
import piniaPersist from 'pinia-plugin-persist'
let pinia = createPinia() //要立即创建,避免后续组件import其他组件需要用到Stores,例如 tabbars
pinia.use(piniaPersist)

//响应式数据存储
import { useUserStore } from '@/stores/user.js'
import { useAppStore } from '@/stores/app.js'
import { usePageParamStore } from '@/stores/pageParams.js'
import { useChatStore } from './lib/chat-storage.js'
import { useDeviceStore } from './stores/device.js'
import { useOfficePostStore } from './stores/office_posts.js' 
  
 //组件
import loginGuard from '@/components/login-guard/login-guard.vue'
import jobCalendar from '@/components/job-calendar/job-calendar.vue'
import statusHeader from '@/components/status-header/status-header.vue'
import loadGurad from '@/components/loading-gurad/loading-gurad.vue'

//表单验证
import Schema from '@/uni_modules/uview-plus/libs/util/async-validator.js'


//本地存储

//动态渲染
// import * as ejs from 'ejs'

// #ifdef H5
let urls = {}
if (process.env.NODE_ENV === 'development') {
	console.log('开发环境');
	urls = {
		// api:'http://192.168.1.6:7008',
		// assets:'http://192.168.1.6:7008',
		// page:'http://192.168.1.4:5173/h5#'
		api:'http://www.apesk.net/api',
		assets:'http://www.apesk.net',
		page:'http://192.168.1.4:5173/h5#'
	}
} else {
	console.log('生产环境');
	urls = window.urls
}

// #endif

// #ifndef H5
let urls = {
	api:'http://192.168.1.6:7008',
	assets:'http://192.168.1.6:7008',
	page:'http://192.168.1.4:5173/h5#'
}
// #endif

console.log(urls)

//接口和网络
import API from '@/utils/api.js'
import Net from '@/utils/net.js'


import Mqtt from './lib/mqttTool.js'

import ChatService from './lib/chat-service.js'

const chatService = new ChatService({
	// #ifdef MP-WEIXIN
		url :'wx://192.168.1.6:8083/mqtt'
	// #endif
	
	// #ifndef MP-WEIXIN
		url :'ws://192.168.1.6:8083/mqtt'
	// #endif
})
 
// import { connect } from "mqtt";

// //const mqtt = require("mqtt");
// const client = connect("ws://192.168.1.6:8083");

// client.on("connect", () => {
//   console.log('on conected!')
//   client.subscribe("chat2", (err) => {
//     if (!err) {
//       client.publish("presence", "Hello mqtt");
//     }
//   });
// });

// client.on("message", (topic, message) => {
//   // message is Buffer
//   console.log(message.toString());
//   //client.end();
// });


//微信公众平台 - 微信H5环境-SDK (需企业认证)
import wx from 'weixin-js-sdk'

// console.log('配置微信SDK')

// wx.config({
// 	"jsApiList":["updateAppMessageShareData","updateTimelineShareData","onMenuShareTimeline"],
// 	"debug":true,
// 	"beta":false,
// 	"openTagList":[],
// 	"appId":"wxdbc056265f3d3392",
// 	"nonceStr":"mF6ZNKbsaE",
// 	"timestamp":"1697761315",
// 	"url":"http://www.apesk.net/h5/#/",
// 	"signature":"cfb5c9572b76399d5fbb628321d3e3b6f1495e34"
// })

// wx.ready(()=>{
// 	console.log('验证成功.')
// })

// wx.error(()=>{
// 	console.log('验证失败.')
// })

import browser from '@/utils/browser.js'
import router from '@/router'
import hook from '@/router/hook.js'

export function createApp() {
	 
	const app = createSSRApp(App);


	app.use(uviewPlus)
	app.use(pinia)
	
	let userStore = useUserStore()
	let appStore = useAppStore()
	let pageParam = usePageParamStore()
	let chatStore = useChatStore()
	let deviceStore = useDeviceStore()
	let officePost = useOfficePostStore()
	
	deviceStore.init()
	
	uni.$on('beforeRouterEnter',(to,from,next)=>{
		console.log('before router enter.')
		next();
	})
	
	
	console.log(deviceStore.measure)
	
	console.log(browser.getAppType())
	
	app.config.globalProperties.$settings = {
		'post_preview_url_root_h5' : 'http://www.apesk.net/h5/',
		'post_preview_uri_h5' : '/pages/job/publish/job-offices/post-manager/post-preview',
	}
	
	app.config.globalProperties.$urls = urls
	app.config.globalProperties.$browser = browser
	app.config.globalProperties.$wxsdk = wx
	app.config.globalProperties.$dayjs_util = dayjs_util
	app.config.globalProperties.$officePost = officePost
	// app.config.globalProperties.$ejs = ejs
	app.config.globalProperties.$dayjs = dayjs
	app.config.globalProperties.$device = deviceStore //reactive(screen)
	app.config.globalProperties.$netTool = netTool
	app.config.globalProperties.$geo = geo
	app.config.globalProperties.$numeral = numeral
	app.config.globalProperties.$lodash = lodash
	app.config.globalProperties.$chatService = chatService
	app.config.globalProperties.$mqttTool = new Mqtt({chatStore})
	app.config.globalProperties.$localStorage = {
		getItem : uni.getStorageSync,
		setItem : uni.setStorageSync,
		removeItem : uni.removeStorageSync
	}
	
	// app.config.globalProperties.LRUCache = LRUCache
	// app.config.globalProperties.$cache5s = cache5s
	// app.config.globalProperties.$cache10s = cache10s
	// app.config.globalProperties.$cache15s = cache15s
	// app.config.globalProperties.$cache30s = cache30s
	// app.config.globalProperties.$cache1m = cache1m
	
	app.config.globalProperties.$API = API
	app.config.globalProperties.$Net = Net
	
	// userStore.token = '26|3Jb6qhHuelVCSkND3yUxpJ0CqPo3yJUZyzCCTuPj'
	// 如此配置即可
	uni.$u.config.unit = 'px'
	
	app.config.globalProperties.$permission = (requires)=>{
		if(!requires) return true
		let permissions =  userStore.baseInfo.roles?userStore.baseInfo.roles:[]
		
		if(requires.includes('user') && userStore.isLogin) return true
		
		console.log(permissions)
		if(requires.includes('all')) return true
		return requires.some(i=>permissions.includes(i))
	}
	
	app.component('loginGuard',loginGuard)
	app.component('jobCalendar',jobCalendar)
	app.component('statusHeader',statusHeader)
	app.component('loadGurad',loadGurad)
	
	//app.component('tabbs',tabbs)
	
	app.mixin({
		computed:{
			permission(){
				return (requires)=>{
					return this.$permission(requires)
				}
			}
		},
		data(){
			return {
				chatStore,
				userStore,
				pageParam,
				isTabbarPermisson:false ,//是否开启Tabbar的权限检测
				StatusBar: 0,
				CustomBar: 60,
				AppStyle:""
			}
		},
		methods:{
			validate(rules,data)
			{
				const schema = new Schema(rules)
				return schema.validate(data)
			},
			
			async saveTempImageToPhotosAlbum(tempFilePath)
			{
				return new Promise((resovle,reject)=>{
					// #ifndef H5
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: res => {
								console.log(res);
								resovle(null)
							},
							fail: err => {
								console.log(err);
							}
						});
					// #endif
					
					// #ifdef H5
						const aEle = document.createElement('a');
						aEle.download = 'uQRCode'; // 设置下载的文件名，默认是'下载'
						aEle.href = tempFilePath;
						document.body.appendChild(aEle);
						aEle.click();
						aEle.remove();
						resovle(null)
					// #endif
				})
	
			},
		
			async saveCanvasToAlbum(canvasId,fileType,canvasWidth,canvasHeight) {
				return new Promise((resovle,reject)=>{
					uni.canvasToTempFilePath(
					    {
					        canvasId: canvasId,
					        fileType: fileType,
					        width: canvasWidth,
					        height: canvasHeight,
					        success: async res => {
					            console.log(res)
								
								resovle(await this.saveTempImageToPhotosAlbum(res.tempFilePath))
								
					        },
					        fail: err => {
					            console.log(err);
					        }
					    }
					    // this // 组件内使用必传当前实例
					);
				})
			},
			async uploadFile(tempFile,imageType="image",storageKey='avatar'){
				return await this.$netTool.handleUploadFile(
					this.absUrl('/api/common/storage/upload'),  //上传接口URL
					tempFile, // 要上传的文件路径
					imageType, //文件类型
					storageKey, // 存储关键字,存储目录名称
					{
						"token":this.userStore.token //headers 加上令牌
					},
				);
			}, 
			async chooseImageToUpload(){
				return new Promise((resolve,reject)=>{
					uni.chooseImage({
						count: 1,
						success: async (res)=>{
							console.log(JSON.stringify(res.tempFilePaths));
							let result = await this.uploadFile(res.tempFilePaths[0])
							console.log(result)
							resolve(result.data.path)
						}
					})
				})
			},
			async chooseVideoToUpload(){
				let that = this
				return new Promise((resolve,reject)=>{
					uni.chooseVideo({
						sourceType: ['camera', 'album'],
						success: async function (res) {
							console.log(JSON.stringify(res.tempFilePath));
							let result = await that.uploadFile(res.tempFilePath,'video')
							console.log(result)
							resolve(result.data.path)
						}
					})
				})
			},
			absUrl(relativeUrl){
				if(relativeUrl == null)
					relativeUrl = ""
				
				if(relativeUrl.indexOf('http') >= 0) {
					return relativeUrl
				}
	
				if(!relativeUrl.startsWith('/')) 
					relativeUrl = '/' + relativeUrl
				
				let url = urls.assets
				// console.log(url)
				// console.log(relativeUrl)
				// console.log(url + relativeUrl)
				return url + relativeUrl
			},
			apiUrl(relativeUrl){
				if(relativeUrl == null)
					relativeUrl = ""
				
				if(relativeUrl.indexOf('http') >= 0) {
					return relativeUrl
				}
			
				if(!relativeUrl.startsWith('/')) 
					relativeUrl = '/' + relativeUrl
				
				let url = urls.api
				// console.log(url)
				// console.log(relativeUrl)
				// console.log(url + relativeUrl)
				return url + relativeUrl
			},
			pageUrl(relativeUrl){
				if(relativeUrl.indexOf('http') >= 0) {
					return relativeUrl
				}
			
				if(!relativeUrl.startsWith('/')) 
					relativeUrl = '/' + relativeUrl
				
				let url = urls.page
				console.log(url)
				console.log(relativeUrl)
				console.log(url + relativeUrl)
				return url + relativeUrl
			},
			currentPageUrl(){
				let pages = getCurrentPages()
				let url = pages[pages.length - 1].route
				return url
			},
			_showLoading(){
				this.$refs.uToast.show({
					type:"loading",
					show:"true",
					message:"正在加载中",
					duration:9999999
				})
			},
			hideLoading()
			{
				this.$refs.uToast.hide()
			},
			showNoMore(){
				this.$refs.uToast.show({
					type:"default",
					show:"true",
					message:"没有更多了",
					duration:1000
				})
			}
		}
	})
	
	
	let http = axiosCreator({
		//#ifdef H5 || APP
			baseURL: '/api',
		//#endif
		
		//#ifndef H5
			//baseURL: 'https://zp.apesk.net',
			baseURL:  urls.api + '/api' ,
		//#endif
		
		timeout:3000
	});
	
	http.interceptors.request.use((request,data)=>{
		// console.log(request)
		// console.log(data)
		if(userStore.token !== undefined && userStore.token !== null && userStore.token !== '')
		{
			request.headers['token'] = userStore.token
			
			console.log(userStore.token)
		}
		
		return request
	})
	
	http.interceptors.response.use(
		(response)=>{
		
			uni.hideLoading()
			
			// console.log(response)
			if(response.data.status < 0)
			{
				uni.showToast({
					title:response.data.message,
					icon:'error'
				})
				
				return Promise.reject(null)
			}
			
			// console.log(response.data.data)
			
			return response.data
		},
		err=>{
				console.log(err)
				uni.showToast({
					title:`${err.message}`,
					icon:'error'
				})
			
			uni.hideLoading()
		}
	)
	
	appStore.app = app
	appStore.http = http
	app.config.globalProperties.$http = http;
	
	// Vue.prototype.$H.interceptors.response.use((res) => {
	// 	return res.data
	// })
	
	
	//自定义指令,除H5、App以外都不支持。
	// 权限检测统一使用 v-if或v-show指令,结合函数式computed属性。
	// app.directive('permission',{
	// 	mounted(el,binding,vnode) {
	// 		console.log(binding)
	// 		setTimeout(()=>{
	// 			vnode.el.hidden = true;
				
	// 			console.log(el)
	// 			console.log(vnode)
	// 		},1000)
	// 	}
	// })
	
	// app.mixin({
	// 	directives:{
	// 		permission(){
				
	// 		}
	// 	}
	// })
	
	// #ifdef H5
	// app.mixin({
	// 	onShow(){
	// 		uni.pageScrollTo({
	// 			scrollTop:0
	// 		})
	// 	}
	// })
	// #endif
	 
	// app.$router.afterEach(() => {
	// 	uni.pageScrollTo({
	// 		scrollTop: 0,//滚动到页面的目标位置
	// 		duration: 0
	// 	});
	// });
	
	hook(router,userStore)

	return {
		app,
		router,
	};
}
